<template>
  <div class="pet-service-management">
    <el-tabs v-model="activeTab" class="mb-4">
      <el-tab-pane label="服务项目设置" name="settings" />
      <el-tab-pane label="服务订单管理" name="orders" />
      <el-tab-pane label="服务质量评价" name="evaluation" />
    </el-tabs>

    <!-- 服务项目设置 -->
    <div v-if="activeTab === 'settings'" class="space-y-6">
      <div class="flex-between mb-4">
        <span class="text-xl font-semibold">服务项目设置</span>
        <el-button type="primary" @click="openAddService">新增服务项目</el-button>
      </div>
      <el-card class="mb-4">
        <el-form :inline="true" :model="searchService">
          <el-form-item label="服务名称">
            <el-input v-model="searchService.name" placeholder="服务名称" />
          </el-form-item>
          <el-form-item label="服务类别">
            <el-select v-model="searchService.category" placeholder="服务类别" clearable style="width: 220px">
              <el-option label="美容" value="美容" />
              <el-option label="医疗" value="医疗" />
              <el-option label="寄养" value="寄养" />
            </el-select>
          </el-form-item>
          <el-form-item label="是否启用">
            <el-select v-model="searchService.enabled" placeholder="是否启用" clearable style="width: 220px">
              <el-option label="启用" value="true" />
              <el-option label="禁用" value="false" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="onSearchService">查询</el-button>
          </el-form-item>
        </el-form>
      </el-card>
      <el-card>
        <el-table :data="displayServices" border stripe>
          <el-table-column prop="name" label="服务名称" />
          <el-table-column prop="category" label="类别" />
          <el-table-column prop="price" label="价格(¥)">
            <template #default="scope">¥{{ (typeof scope.row.price === 'number' ? scope.row.price : 0).toFixed(2)
            }}</template>
          </el-table-column>
          <el-table-column prop="duration" label="时长(分钟)" />
          <el-table-column prop="enabled" label="是否启用">
            <template #default="scope">
              <el-tag :type="scope.row.enabled ? 'success' : 'danger'">{{ scope.row.enabled ? '启用' : '禁用' }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template #default="scope">
              <el-button type="primary" link @click="onEditService(scope.row)">编辑</el-button>
              <el-button type="danger" link @click="onDeleteService(scope.row)">删除</el-button>
              <el-button v-if="scope.row.enabled" type="success" link @click="onOrderService(scope.row)">下单</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination class="mt-4" :current-page="servicePagination.pageNum" :page-size="servicePagination.pageSize"
          :total="servicePagination.total" layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleServiceSizeChange" @current-change="handleServiceCurrentChange" />
      </el-card>
    </div>

    <!-- 服务订单管理 -->
    <div v-if="activeTab === 'orders'" class="space-y-6">
      <div class="flex-between mb-4">
        <span class="text-xl font-semibold">服务订单管理</span>
        <div>
        </div>
      </div>
      <el-card class="mb-4">
        <el-form :inline="true" :model="searchOrder">
          <el-form-item label="客户姓名">
            <el-input v-model="searchOrder.customerName" placeholder="客户姓名" />
          </el-form-item>
          <el-form-item label="订单状态">
            <el-select v-model="searchOrder.status" placeholder="订单状态" clearable style="width: 220px">
              <el-option label="待处理" value="待处理" />
              <el-option label="进行中" value="进行中" />
              <el-option label="已完成" value="已完成" />
              <el-option label="已取消" value="已取消" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="onSearchOrder">查询</el-button>
          </el-form-item>
        </el-form>
      </el-card>
      <el-card>
        <el-table :data="displayOrders" border stripe>
          <el-table-column prop="customerName" label="客户姓名" />
          <el-table-column prop="petName" label="宠物" />
          <el-table-column prop="serviceName" label="服务" />
          <el-table-column prop="employeeName" label="服务员工" />
          <el-table-column prop="status" label="状态">
            <template #default="scope">
              <el-tag :type="orderStatusTag(scope.row.status)">{{ scope.row.status }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="actualAmount" label="实收金额">
            <template #default="scope">¥{{ (typeof scope.row.actualAmount === 'number' ? scope.row.actualAmount :
              0).toFixed(2) }}</template>
          </el-table-column>
          <el-table-column label="操作">
            <template #default="scope">
              <el-button type="primary" link @click="onEditOrder(scope.row)">编辑</el-button>
              <el-button type="danger" link @click="onDeleteOrder(scope.row)">删除</el-button>
              <el-button v-if="scope.row.status === '已完成'" type="success" link @click="onAddEvaluation(scope.row)">评价</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination class="mt-4" :current-page="orderPagination.pageNum" :page-size="orderPagination.pageSize"
          :total="orderPagination.total" layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleOrderSizeChange" @current-change="handleOrderCurrentChange" />
      </el-card>
      <!-- 编辑服务订单弹窗 -->
      <el-dialog v-model="showEditOrderModal" title="编辑服务订单" width="500px">
        <el-form ref="editOrderFormRef" :model="formOrder" label-width="100px">
          <el-form-item label="客户姓名">
            <el-input v-model="formOrder.customerName" readonly />
          </el-form-item>
          <el-form-item label="服务员工">
            <el-select v-model="formOrder.employeeId" placeholder="请选择员工" filterable>
              <el-option v-for="e in employeeStore.employees" :key="e.employeeId" :label="e.name" :value="String(e.employeeId)" />
            </el-select>
          </el-form-item>
          <el-form-item label="宠物名称">
            <el-select v-model="formOrder.petId" placeholder="请选择宠物" :disabled="!formOrder.customerId">
              <el-option v-for="pet in petsOfSelectedEditCustomer" :key="pet.id" :label="pet.name" :value="String(pet.id)" />
            </el-select>
          </el-form-item>
          <el-form-item label="服务">
            <el-select v-model="formOrder.serviceItemId" placeholder="请选择服务">
              <el-option v-for="s in serviceItems" :key="s.id" :label="s.name" :value="String(s.id)" />
            </el-select>
          </el-form-item>
          
          <el-form-item label="客户要求">
            <el-input v-model="formOrder.customerRequirement" />
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="formOrder.status" placeholder="请选择">
              <el-option label="待处理" value="待处理" />
              <el-option label="进行中" value="进行中" />
              <el-option label="已完成" value="已完成" />
              <el-option label="已取消" value="已取消" />
            </el-select>
          </el-form-item>
          <el-form-item label="实收金额">
            <el-input-number v-model="formOrder.actualAmount" :min="0" :step="0.01" />
          </el-form-item>
          <el-form-item label="备注">
            <el-input v-model="formOrder.note" />
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="showEditOrderModal = false">取消</el-button>
          <el-button type="primary" @click="onSaveOrder">保存</el-button>
        </template>
      </el-dialog>
    </div>

    <!-- 服务质量评价 -->
    <div v-if="activeTab === 'evaluation'" class="space-y-6">
      <div class="flex-between mb-4">
        <span class="text-xl font-semibold">服务质量评价</span>
      </div>
      <el-card class="mb-4">
        <el-form :inline="true" :model="searchEval">
          <el-form-item label="服务名称">
            <el-input v-model="searchEval.serviceName" placeholder="服务名称" />
          </el-form-item>
          <el-form-item label="评分区间">
            <el-select v-model="searchEval.score" placeholder="评分区间" clearable style="width: 220px">
              <el-option label="5星" value="5" />
              <el-option label="4星" value="4" />
              <el-option label="3星" value="3" />
              <el-option label="2星" value="2" />
              <el-option label="1星" value="1" />
            </el-select>
          </el-form-item>
          <el-form-item label="日期">
            <el-date-picker v-model="searchEval.date" type="date" placeholder="日期" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="onSearchEval">查询</el-button>
          </el-form-item>
        </el-form>
      </el-card>
      <el-row :gutter="24" class="mb-4">
        <el-col :span="8">
          <el-card>
            <div class="text-lg font-semibold mb-2">服务态度</div>
            <div class="text-3xl font-bold mb-2" style="color:#1976d2">{{ evalStatsState.serviceAttitude.avg || 0 }}</div>
            <div class="flex items-center">
              <span class="star">{{ starString(Math.round(evalStatsState.serviceAttitude.avg || 0)) }}</span>
              <span class="ml-2 text-sm text-gray-500">({{ evalStatsState.serviceAttitude.count || 0 }}条评价)</span>
            </div>
          </el-card>
        </el-col>
        <el-col :span="8">
          <el-card>
            <div class="text-lg font-semibold mb-2">技术水平</div>
            <div class="text-3xl font-bold mb-2" style="color:#388e3c">{{ evalStatsState.technicalLevel.avg || 0 }}</div>
            <div class="flex items-center">
              <span class="star">{{ starString(Math.round(evalStatsState.technicalLevel.avg || 0)) }}</span>
              <span class="ml-2 text-sm text-gray-500">({{ evalStatsState.technicalLevel.count || 0 }}条评价)</span>
            </div>
          </el-card>
        </el-col>
        <el-col :span="8">
          <el-card>
            <div class="text-lg font-bold mb-2">环境卫生</div>
            <div class="text-3xl font-bold mb-2" style="color:#8e24aa">{{ evalStatsState.environmentHygiene.avg || 0 }}</div>
            <div class="flex items-center">
              <span class="star">{{ starString(Math.round(evalStatsState.environmentHygiene.avg || 0)) }}</span>
              <span class="ml-2 text-sm text-gray-500">({{ evalStatsState.environmentHygiene.count || 0 }}条评价)</span>
            </div>
          </el-card>
        </el-col>
      </el-row>
      <el-card>
        <el-table :data="displayEvals" border stripe>
          <el-table-column prop="serviceName" label="服务名称" />
          <el-table-column prop="customerName" label="客户姓名" />
          <el-table-column prop="petName" label="宠物名称" />
          <el-table-column prop="employeeName" label="服务员工" />
          <el-table-column prop="serviceAttitude" label="服务态度">
            <template #default="scope">
              <span class="star">{{ starString(scope.row.serviceAttitude) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="technicalLevel" label="技术水平">
            <template #default="scope">
              <span class="star">{{ starString(scope.row.technicalLevel) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="environmentHygiene" label="环境卫生">
            <template #default="scope">
              <span class="star">{{ starString(scope.row.environmentHygiene) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="reviewTimeFormatted" label="评价时间" />
          <el-table-column label="操作">
            <template #default="scope">
              <el-button type="primary" link @click="onViewEval(scope.row)">查看详情</el-button>
              <el-button type="success" link @click="onReplyEval(scope.row)">回复</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination class="mt-4" :current-page="evalPagination.pageNum" :page-size="evalPagination.pageSize"
          :total="evalPagination.total" layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleEvalSizeChange" @current-change="handleEvalCurrentChange" />
      </el-card>
      <!-- 评价详情弹窗 -->
      <el-dialog v-model="showEvalDetailModal" title="评价详情" width="500px">
        <el-descriptions :column="1" v-if="currentEval">
          <el-descriptions-item label="服务名称">{{ currentEval.serviceName }}</el-descriptions-item>
          <el-descriptions-item label="客户姓名">{{ currentEval.customerName }}</el-descriptions-item>
          <el-descriptions-item label="宠物名称">{{ currentEval.petName }}</el-descriptions-item>
          <el-descriptions-item label="服务员工">{{ currentEval.employeeName }}</el-descriptions-item>
          <el-descriptions-item label="服务态度"><span class="star">{{ starString(currentEval.serviceAttitude)
          }}</span></el-descriptions-item>
          <el-descriptions-item label="技术水平"><span class="star">{{ starString(currentEval.technicalLevel)
          }}</span></el-descriptions-item>
          <el-descriptions-item label="环境卫生"><span class="star">{{ starString(currentEval.environmentHygiene)
          }}</span></el-descriptions-item>
          <el-descriptions-item label="评价内容">{{ currentEval.textReview }}</el-descriptions-item>
          <el-descriptions-item label="评价时间">{{
            Array.isArray(currentEval.reviewTime)
              ? dayjs(new Date(currentEval.reviewTime[0], currentEval.reviewTime[1] - 1, currentEval.reviewTime[2], currentEval.reviewTime[3] || 0, currentEval.reviewTime[4] || 0, currentEval.reviewTime[5] || 0)).format('YYYY-MM-DD HH:mm')
              : (currentEval.reviewTime
                  ? (dayjs(currentEval.reviewTime).isValid() ? dayjs(currentEval.reviewTime).format('YYYY-MM-DD HH:mm') : currentEval.reviewTime)
                  : '-')
          }}</el-descriptions-item>
        </el-descriptions>
        <template #footer>
          <el-button @click="showEvalDetailModal = false">关闭</el-button>
        </template>
      </el-dialog>
    </div>

    <!-- 新增服务项目弹窗 -->
    <el-dialog v-model="showAddModal" title="新增服务项目" width="500px">
      <el-form label-width="100px">
        <el-form-item label="服务名称*">
          <el-input v-model="formService.name" />
        </el-form-item>
        <el-form-item label="服务类别*">
          <el-select v-model="formService.category" placeholder="请选择">
            <el-option label="美容" value="美容" />
            <el-option label="医疗" value="医疗" />
            <el-option label="寄养" value="寄养" />
          </el-select>
        </el-form-item>
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="价格(¥)*">
              <el-input v-model="formService.price" type="number" step="0.01" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="时长(分钟)*">
              <el-input v-model="formService.duration" type="number" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="服务流程">
          <el-input v-model="formService.process" type="textarea" rows="2" />
        </el-form-item>
        <el-form-item>
          <el-checkbox v-model="formService.enabled">启用此服务项目</el-checkbox>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="closeDialog">取消</el-button>
        <el-button type="primary" @click="onSaveService">保存</el-button>
      </template>
    </el-dialog>

    <!-- 新增服务质量评价弹窗（最外层，未被tab包裹） -->
    <el-dialog v-model="showAddEvalModal" title="新增服务质量评价" width="500px">
      <el-form :model="evalForm" label-width="100px">
        <el-form-item label="客户姓名">
          <el-input v-model="evalForm.customerName" readonly />
        </el-form-item>
        <el-form-item label="宠物名称">
          <el-input v-model="evalForm.petName" readonly />
        </el-form-item>
        <el-form-item label="服务名称">
          <el-input v-model="evalForm.serviceName" readonly />
        </el-form-item>
        <el-form-item label="服务员工">
          <el-input v-model="evalForm.employeeName" readonly />
        </el-form-item>
        <el-form-item label="服务态度">
          <el-rate v-model="evalForm.serviceAttitude" :max="5" />
        </el-form-item>
        <el-form-item label="技术水平">
          <el-rate v-model="evalForm.technicalLevel" :max="5" />
        </el-form-item>
        <el-form-item label="环境卫生">
          <el-rate v-model="evalForm.environmentHygiene" :max="5" />
        </el-form-item>
        <el-form-item label="评价内容">
          <el-input v-model="evalForm.textReview" type="textarea" :rows="3" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showAddEvalModal = false">取消</el-button>
        <el-button type="primary" @click="onSaveEvaluation">保存</el-button>
      </template>
    </el-dialog>

    <!-- 新建服务订单弹窗（最外层，未被tab包裹） -->
    <el-dialog v-model="showAddOrderModal" title="新建服务订单" width="500px">
      <el-form ref="orderFormRef" :model="formAddOrder" label-width="100px">
        <div style="margin-bottom: 8px; color: #888; font-size: 13px;">客户数量：{{ customerStore.customers.length }}，员工数量：{{
          employeeStore.employees.length }}</div>
        <el-form-item label="选择客户">
          <el-select v-model="formAddOrder.customerId" placeholder="请选择客户" filterable @change="onCustomerChange">
            <el-option v-for="c in customerStore.customers" :key="c.id" :label="c.name" :value="String(c.id)" />
          </el-select>
        </el-form-item>
        <el-form-item label="选择员工">
          <el-select v-model="formAddOrder.employeeId" placeholder="请选择员工" filterable @change="onEmployeeChange">
            <el-option v-for="e in employeeStore.employees" :key="e.employeeId" :label="e.name" :value="String(e.employeeId)" />
          </el-select>
        </el-form-item>
        <el-form-item label="宠物名称">
          <el-select v-model="formAddOrder.petId" placeholder="请选择宠物" :disabled="!formAddOrder.customerId">
            <el-option v-for="pet in petsOfSelectedCustomer" :key="pet.id" :label="pet.name" :value="String(pet.id)" />
          </el-select>
        </el-form-item>
        <el-form-item label="服务">
          <el-select v-model="formAddOrder.serviceItemId" placeholder="请选择服务" @change="onServiceChange">
            <el-option v-for="s in serviceItems" :key="s.id" :label="s.name" :value="String(s.id)" />
          </el-select>
        </el-form-item>
        <el-form-item label="实收金额">
          <el-input-number v-model="formAddOrder.actualAmount" :min="0" :step="0.01" :disabled="true" />
        </el-form-item>
        <el-form-item label="客户要求">
          <el-input v-model="formAddOrder.customerRequirement" />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="formAddOrder.status" placeholder="请选择">
            <el-option label="待处理" value="待处理" />
            <el-option label="进行中" value="进行中" />
            <el-option label="已完成" value="已完成" />
            <el-option label="已取消" value="已取消" />
          </el-select>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="formAddOrder.note" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showAddOrderModal = false">取消</el-button>
        <el-button type="primary" @click="onSaveAddOrder">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch, computed, toRefs } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import dayjs from 'dayjs';
import { useCustomerStore } from '@/stores/customerStore';
import { useEmployeeStore } from '@/stores/employeeStore';
import { useOrderStore } from '@/stores/orderStore';
import { useMemberStore } from '@/stores/memberStore';
import { useConsumptionStore } from '@/stores/consumptionStore';
import {
  getServiceList,
  addService,
  updateService,
  deleteService,
  getEvaluationList,
  addEvaluation,
  deleteEvaluation,
  getEvaluationStats
} from '@/api/service';

const activeTab = ref('settings');
const showAddModal = ref(false);
const editingService = ref(null);

const showEditOrderModal = ref(false);
const formOrder = reactive({
  id: '',
  customerId: '',
  employeeId: '',
  petId: '',
  serviceItemId: '',
  customerName: '',
  petName: '',
  serviceName: '',
  customerRequirement: '',
  status: '',
  actualAmount: 0,
  note: ''
});

const showAddOrderModal = ref(false);
const formAddOrder = reactive({
  customerId: '',
  employeeId: '',
  petId: '',
  serviceItemId: '',
  customerRequirement: '',
  status: '',
  actualAmount: 0,
  note: ''
});

const showEvalDetailModal = ref(false);
const currentEval = ref(null);

const searchService = reactive({ name: '', category: '', enabled: '', pageNum: 1, pageSize: 10 });
const searchOrder = reactive({ customerName: '', status: '', pageNum: 1, pageSize: 10 });
const searchEval = reactive({ serviceName: '', score: '', date: '', pageNum: 1, pageSize: 10 });

const serviceItems = ref([]);
const servicePagination = reactive({
  pageNum: 1,
  pageSize: 10,
  total: 0,
});
const displayServices = computed(() => serviceItems.value);

const orderStore = useOrderStore();
const displayOrders = computed(() => orderStore.orders);
const orderPagination = reactive({
  pageNum: 1,
  pageSize: 10,
  total: 0,
});

const evaluations = ref([]);
const allEvaluations = ref([]);
const evalPagination = reactive({
  pageNum: 1,
  pageSize: 10,
  total: 0,
});
const displayEvals = computed(() => {
  return evaluations.value.map(e => ({
    ...e,
    reviewTimeFormatted: Array.isArray(e.reviewTime)
      ? dayjs(new Date(e.reviewTime[0], e.reviewTime[1] - 1, e.reviewTime[2], e.reviewTime[3] || 0, e.reviewTime[4] || 0, e.reviewTime[5] || 0)).format('YYYY-MM-DD HH:mm')
      : (e.reviewTime
          ? (dayjs(e.reviewTime).isValid() ? dayjs(e.reviewTime).format('YYYY-MM-DD HH:mm') : e.reviewTime)
          : '-')
  }));
});

const formService = reactive({
  name: '',
  category: '',
  price: '',
  duration: '',
  process: '',
  enabled: true,
});

const orderFormRef = ref();

const showAddEvalModal = ref(false);
const evalForm = reactive({
  orderId: '',
  customerId: '',
  employeeId: '',
  serviceItemId: '',
  customerName: '',
  petName: '',
  serviceName: '',
  employeeName: '',
  serviceAttitude: 5,
  technicalLevel: 5,
  environmentHygiene: 5,
  textReview: '',
  reviewTime: ''
});

const customerStore = useCustomerStore();
const employeeStore = useEmployeeStore();
const memberStore = useMemberStore();
const consumptionStore = useConsumptionStore();

// 统计卡片数据
const evalStatsState = reactive({
  serviceAttitude: { avg: 0, count: 0 },
  technicalLevel: { avg: 0, count: 0 },
  environmentHygiene: { avg: 0, count: 0 }
});
const evalStats = toRefs(evalStatsState);

onMounted(() => {
  fetchServices();
  fetchOrders();
  fetchEvals();
  fetchAllEvals();
});

// petsOfSelectedCustomer 依赖 customers.value
const petsOfSelectedCustomer = computed(() => {
  const c = customerStore.customers.find(c => c.id === formAddOrder.customerId);
  return c ? c.pets || [] : [];
});

// 新增：编辑订单弹窗专用宠物列表
const petsOfSelectedEditCustomer = computed(() => {
  const c = customerStore.customers.find(c => String(c.id) === String(formOrder.customerId));
  return c ? c.pets || [] : [];
});

watch(activeTab, (newTab) => {
  if (newTab === 'settings') {
    fetchServices();
  } else if (newTab === 'orders') {
    fetchOrders();
  } else if (newTab === 'evaluation') {
    fetchEvals();
  }
});

// --- 数据获取 ---
async function fetchServices() {
  const res = await getServiceList({ ...searchService, pageNum: servicePagination.pageNum, pageSize: servicePagination.pageSize });
  serviceItems.value = res.data?.data || [];
  servicePagination.total = res.data?.total || 0;
}

async function fetchOrders() {
  await orderStore.fetchOrders({ ...searchOrder, pageNum: orderPagination.pageNum, pageSize: orderPagination.pageSize });
  orderPagination.total = orderStore.orders.length; // 若后端返回total可直接赋值
  console.log('【DEBUG】orderStore.orders:', orderStore.orders);
}

async function fetchEvals() {
  const res = await getEvaluationList({ ...searchEval, pageNum: evalPagination.pageNum, pageSize: evalPagination.pageSize });
  evaluations.value = res.data?.data || [];
  console.log('【DEBUG】evaluations.value:', evaluations.value);
  evalPagination.total = res.data?.total || 0;
  // 拉取统计
  await fetchEvalStats();
}

async function fetchAllEvals() {
  // 先拉第一页，获取总数
  const firstRes = await getEvaluationList({ ...searchEval, pageNum: 1, pageSize: 10 });
  const total = firstRes.data?.total || 0;
  const pageSize = 10;
  const pageCount = Math.ceil(total / pageSize);
  let all = firstRes.data?.data || [];
  // 如果只有一页，直接用
  if (pageCount <= 1) {
    allEvaluations.value = all;
    return;
  }
  // 否则循环拉取剩余页
  const promises = [];
  for (let i = 2; i <= pageCount; i++) {
    promises.push(getEvaluationList({ ...searchEval, pageNum: i, pageSize }));
  }
  const results = await Promise.all(promises);
  results.forEach(res => {
    all = all.concat(res.data?.data || []);
  });
  allEvaluations.value = all;
}

function openAddService() {
  editingService.value = null;
  Object.keys(formService).forEach(k => formService[k] = k === 'enabled' ? true : '');
  showAddModal.value = true;
}
function onEditService(row) {
  Object.keys(formService).forEach(k => formService[k] = row[k] ?? (k === 'enabled' ? true : ''));
  editingService.value = row;
  showAddModal.value = true;
}
function closeDialog() {
  showAddModal.value = false;
  editingService.value = null;
  Object.keys(formService).forEach(k => formService[k] = k === 'enabled' ? true : '');
}
function onSearchService() {
  servicePagination.pageNum = 1;
  fetchServices();
}
async function onDeleteService(row) {
  await ElMessageBox.confirm(`确定要删除服务项目 ${row.name} 吗？`, '确认删除', {
    confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning'
  });
  await deleteService(row.id);
  ElMessage.success('服务项目已删除');
  fetchServices();
}
async function onSaveService() {
  if (editingService.value) {
    await updateService({ ...formService, id: editingService.value.id });
    ElMessage.success('服务项目已更新');
  } else {
    await addService({ ...formService });
    ElMessage.success('新增服务项目成功');
  }
  closeDialog();
  fetchServices();
}
function onExportSchedule() {
  ElMessage.info('点击了导出排班表');
}
function onAddOrder() {
  ElMessage.info('点击了新建订单');
}
function onSearchOrder() {
  orderPagination.pageNum = 1;
  fetchOrders();
}
function onEditOrder(row) {
  formOrder.id = row.id;
  formOrder.customerId = row.customerId !== undefined ? String(row.customerId) : (row.customer_id !== undefined ? String(row.customer_id) : '');
  formOrder.employeeId = row.employeeId || row.employee_id ? String(row.employeeId || row.employee_id) : '';
  formOrder.petId = row.petId || row.pet_id ? String(row.petId || row.pet_id) : '';
  formOrder.serviceItemId = row.serviceItemId || row.service_item_id ? String(row.serviceItemId || row.service_item_id) : '';
  formOrder.customerRequirement = row.customerRequirement || row.customer_requirement || '';
  formOrder.status = row.status;
  formOrder.actualAmount = row.actualAmount || row.actual_amount || 0;
  formOrder.note = row.note || '';
  formOrder.customerName = row.customerName || row.customer_name || '';
  formOrder.petName = row.petName || row.pet_name || '';
  formOrder.serviceName = row.serviceName || row.service_name || '';
  // 调试输出
  console.log('【DEBUG】onEditOrder row:', row);
  console.log('【DEBUG】formOrder.customerId:', formOrder.customerId);
  console.log('【DEBUG】customerStore.customers:', customerStore.customers);
  console.log('【DEBUG】petsOfSelectedEditCustomer:', petsOfSelectedEditCustomer.value);
  showEditOrderModal.value = true;
}
async function onDeleteOrder(row) {
  await ElMessageBox.confirm(`确定要删除订单吗？`, '确认删除', {
    confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning'
  });
  await orderStore.deleteOrder(row.id);
  ElMessage.success('订单已删除');
  fetchOrders();
}
const editOrderFormRef = ref();
async function onSaveOrder() {
  await orderStore.updateOrder(formOrder.id, {
    ...formOrder,
    transactionDate: dayjs().format('YYYY-MM-DD')
  });
  // 新增：同步写入财务管理用订单信息（mock编号只用于前端展示，不作为id传递后端）
  orderStore.addOrder({
    id: formOrder.id, // 这里id保持原有主键类型
    orderNumber: `${dayjs().format('YYYYMMDDHHmmss')}`, // 仅orderNumber用字符串
    incomeType: '服务收费',
    customerName: formOrder.customerName,
    employeeName: employeeStore.employees.find(e => String(e.employeeId) === String(formOrder.employeeId))?.name || '',
    amount: formOrder.actualAmount,
    transactionDate: dayjs().format('YYYY-MM-DD'),
    orderStatus: formOrder.status,
    note: formOrder.note || ''
  });
  ElMessage.success('订单已更新');
  showEditOrderModal.value = false;
  fetchOrders();
}
async function onSaveAddOrder() {
  // 真实下单，向后端发请求
  await orderStore.addOrder({
    ...formAddOrder,
    transactionDate: dayjs().format('YYYY-MM-DD')
  }); // 不传 true，默认 mockOnly=false
  // 新增：同步写入财务管理用订单信息（mock，不请求接口）
  orderStore.addOrder({
    id: formAddOrder.id || Date.now(), // id用数字或后端主键
    orderNumber: `ORD${dayjs().format('YYYYMMDDHHmmss')}`,
    incomeType: '服务收费',
    customerName: customerStore.customers.find(c => c.id === formAddOrder.customerId)?.name || '',
    employeeName: employeeStore.employees.find(e => String(e.employeeId) === String(formAddOrder.employeeId))?.name || '',
    amount: formAddOrder.actualAmount,
    transactionDate: dayjs().format('YYYY-MM-DD'),
    orderStatus: formAddOrder.status,
    note: formAddOrder.note || ''
  }, true); // mockOnly=true
  ElMessage.success('订单已添加');
  showAddOrderModal.value = false;
  resetAddOrderForm();
  fetchOrders();
}
function resetAddOrderForm() {
  Object.keys(formAddOrder).forEach(k => {
    if (typeof formAddOrder[k] === 'number') formAddOrder[k] = 0;
    else formAddOrder[k] = '';
  });
}
function onSearchEval() {
  evalPagination.pageNum = 1;
  fetchEvals();
}
function onViewEval(row) {
  currentEval.value = row;
  showEvalDetailModal.value = true;
}
function onReplyEval(row) {
  ElMessage.info('点击了回复: ' + row.customerName);
}
async function onDeleteEval(row) {
  await ElMessageBox.confirm(`确定要删除评价吗？`, '确认删除', {
    confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning'
  });
  await deleteEvaluation(row.id);
  ElMessage.success('评价已删除');
  fetchEvals();
}
function orderStatusTag(status) {
  if (status === '已完成') return 'success';
  if (status === '进行中') return 'info';
  if (status === '待处理') return 'warning';
  if (status === '已取消') return 'danger';
  return '';
}
function starString(num) {
  return '★'.repeat(num) + '☆'.repeat(5 - num);
}
// --- 分页处理 ---
async function handleServiceSizeChange(val) {
  servicePagination.pageSize = val;
  await fetchServices();
}
async function handleServiceCurrentChange(val) {
  servicePagination.pageNum = val;
  await fetchServices();
}
async function handleOrderSizeChange(val) {
  orderPagination.pageSize = val;
  await fetchOrders();
}
async function handleOrderCurrentChange(val) {
  orderPagination.pageNum = val;
  await fetchOrders();
}
async function handleEvalSizeChange(val) {
  evalPagination.pageSize = val;
  await fetchEvals();
}
async function handleEvalCurrentChange(val) {
  evalPagination.pageNum = val;
  await fetchEvals();
}
function onAddEvaluation(order) {
  evalForm.orderId = order.id || order.orderId || order.order_id || '';
  evalForm.customerId = order.customerId || order.customer_id || '';
  evalForm.employeeId = order.employeeId || order.employee_id || '';
  evalForm.serviceItemId = order.serviceItemId || order.service_item_id || '';
  evalForm.customerName = order.customerName || order.customer_name || '';
  evalForm.petName = order.petName || order.pet_name || '';
  evalForm.serviceName = order.serviceName || order.service_name || '';
  evalForm.employeeName = order.employeeName || order.employee_name || '';
  evalForm.serviceAttitude = 5;
  evalForm.technicalLevel = 5;
  evalForm.environmentHygiene = 5;
  evalForm.textReview = '';
  evalForm.reviewTime = dayjs().format('YYYY-MM-DDTHH:mm:ss');
  showAddEvalModal.value = true;
}
async function onSaveEvaluation() {
  await addEvaluation({
    orderId: evalForm.orderId,
    customerId: evalForm.customerId,
    employeeId: evalForm.employeeId,
    serviceItemId: evalForm.serviceItemId,
    serviceAttitude: evalForm.serviceAttitude,
    technicalLevel: evalForm.technicalLevel,
    environmentHygiene: evalForm.environmentHygiene,
    textReview: evalForm.textReview,
    reviewTime: dayjs().format('YYYY-MM-DDTHH:mm:ss')
  });
  ElMessage.success('评价已添加');
  showAddEvalModal.value = false;
  fetchEvals();
  activeTab.value = 'evaluation';
}
function onOrderService(service) {
  showAddOrderModal.value = true;
  formAddOrder.serviceItemId = service.id;
  formAddOrder.serviceName = service.name;
  onServiceChange(service.id);
  formAddOrder.customerId = '';
  formAddOrder.customerName = '';
  formAddOrder.employeeId = '';
  formAddOrder.employeeName = '';
  formAddOrder.petId = '';
}
function onCustomerChange(id) {
  const c = customerStore.customers.find(c => c.id === id);
  formAddOrder.customerName = c ? c.name : '';
  formAddOrder.petId = '';
}
function onEmployeeChange(id) {
  formAddOrder.employeeId = String(id);
  const e = employeeStore.employees.find(e => String(e.employeeId) === String(id));
  formAddOrder.employeeName = e ? e.name : '';
}
function onServiceChange(serviceId) {
  const s = serviceItems.value.find(s => s.id === serviceId);
  formAddOrder.actualAmount = s ? s.price : 0;
}

// 拉取统计
async function fetchEvalStats() {
  const params = {
    serviceName: searchEval.serviceName,
    date: searchEval.date
  };
  const res = await getEvaluationStats(params);
  console.log('[DEBUG] getEvaluationStats res:', res);
  console.log('[DEBUG] getEvaluationStats res.data:', res.data);
  // 修正：直接取 res.data
  const data = res.data || {};
  evalStatsState.serviceAttitude = { avg: data.avgServiceAttitude || 0, count: data.totalCount || 0 };
  evalStatsState.technicalLevel = { avg: data.avgTechnicalLevel || 0, count: data.totalCount || 0 };
  evalStatsState.environmentHygiene = { avg: data.avgEnvironmentHygiene || 0, count: data.totalCount || 0 };
  console.log('[DEBUG] evalStatsState:', evalStatsState);
}

function openAddOrder() {
  // 调试：打印员工列表
  console.log('[调试] 当前员工列表:', JSON.parse(JSON.stringify(employeeStore.employees)));
  showAddOrderModal.value = true;
}
</script>

<style scoped>
.pet-service-management {
  padding: 24px;
}

.flex-between {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.space-y-6>*+* {
  margin-top: 24px;
}

.star {
  color: #fbc02d;
  font-size: 18px;
  letter-spacing: 1px;
}
</style>